<template>
  <div class="container">
    <!-- 新增弹框 -->
    <el-dialog
      :title="this.form.id ? '修改学科' : '新增学科'"
      :visible="showDialog"
      @close="closeDialog"
      style="width: 60%; margin-left: 250px"
    >
      <!-- 表单 -->
      <el-form :model="form" :rules="rules" ref="formsub">
        <el-form-item label="学科名称" prop="subjectName">
          <el-input
            style="width: 70%"
            placeholder="请输入学科名称"
            v-model="form.subjectName"
          />
        </el-form-item>
        <el-form-item label="是否显示">
          <el-switch
            v-model="form.isFrontDisplay"
            active-color="#13ce66"
            inactive-color="#ff4949"
          >
          </el-switch>
        </el-form-item>
        <!-- footer插槽 -->
        <el-form-item class="footer">
          <el-button @click="closeDialog">取消</el-button>
          <el-button type="primary" @click="confirm">确定</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
import { add, update, detail } from '@/api/hmmm/subjects'
export default {
  props: {
    showDialog: {
      type: Boolean,
      default: false
    }
  },
  data () {
    return {
      form: {
        isFrontDisplay: true,
        subjectName: ''
      },
      rules: {
        subjectName: [
          { required: true, message: '请输入学科名称', trigger: 'blur' },
          { min: 1, max: 5, message: '长度在 1 到 5 个字符', trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    // 关闭弹框
    closeDialog () {
      this.$emit('closeDialog')
      this.form = {
        isFrontDisplay: true,
        subjectName: ''
      }
      this.$refs.formsub.resetFields()
    },
    // 确定按钮
    confirm () {
      this.$refs.formsub.validate(async (valid) => {
        if (valid) {
          if (this.form.id) {
            await update(this.form)
            this.$message({
              type: 'success',
              message: '修改成功'
            })
          } else {
            await add(this.form)
            this.$message({
              type: 'success',
              message: '新增成功'
            })
          }
          // 3. 通知父组件更新列表
          this.$emit('update-list')
          // 关闭弹框
          this.closeDialog()
        }
      })
    },
    // 回显数据
    async getDetail (id) {
      const res = await detail({ id })
      // console.log(res);
      this.form = res.data
      // 转化成布尔值
      this.form.isFrontDisplay = !!this.form.isFrontDisplay
    }
  }
}
</script>

<style scoped lang='scss'>
.footer {
  text-align: right;
}
</style>
